package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.NoScrollGridAdapter;
import com.wbao.dianniu.adapter.QuestAnswerAdapter;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.MyListView;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.data.QuestAnswerCountsData;
import com.wbao.dianniu.data.QuestAnswerListData;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.listener.IAddorDelCollectListener;
import com.wbao.dianniu.listener.IAnswerDeleteListener;
import com.wbao.dianniu.listener.IPraiseListener;
import com.wbao.dianniu.listener.IQuestAnswerListListener;
import com.wbao.dianniu.listener.IQuestAnswerListener;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.listener.IQuestDetailListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.AddorDelCollectManager;
import com.wbao.dianniu.manager.AnswerDeleteManger;
import com.wbao.dianniu.manager.BrowseAddManger;
import com.wbao.dianniu.manager.PraiseManger;
import com.wbao.dianniu.manager.QAnswerListManger;
import com.wbao.dianniu.update.QaDataChangeManager;
import com.wbao.dianniu.manager.QuestAnswerManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestDetailManager;
import com.wbao.dianniu.update.ShareSDKManager;
import com.wbao.dianniu.scrollview.PullToRefreshView;
import com.wbao.dianniu.scrollview.PullToRefreshView.OnFooterRefreshListener;
import com.wbao.dianniu.update.ErrorDialogHelper;
import com.wbao.dianniu.utils.CommentLongClickHelper;
import com.wbao.dianniu.utils.JsonUtil;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.ReplyHelper;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问答详情页
 *
 * @author yejianjun
 */
public class QaDetailActivity extends AppCompatActivity implements IQuestAnswerListListener, IPraiseListener, IQuestAnswerListener,
        IAddorDelCollectListener, IAnswerDeleteListener, OnFooterRefreshListener, OnClickListener, ReplyHelper.ReplyListener
        , IQuestDelListener, IQuestDetailListener, CommentLongClickHelper.ICommentLongListener {

    private LinearLayout waittingLayout;
    private ProgressBar waittingProBar;
    private TextView waittingTV;

    /**
     * 标题左侧的返回皱键
     */
    private ImageButton backBtn;
    /**
     * 标题
     */
    private TextView titleTV;
    /**
     * 标题右边图片
     */
    private ImageButton rightImageBtn;
    /**
     * 头像
     */
    private ImageView headIV;
    /**
     * 昵称
     */
    public TextView nameTV;
    /**
     * 标签
     */
    private TextView labelTV;
    private ImageView sexIV;
    private ImageView addV;
    /**
     * 内容
     */
    public SpanTextView contentTV;
    /**
     * 被看过数
     */
    public TextView visitorTV;
    /**
     * 点赞数
     */
    public TextView praiseTV;
    /**
     * 回复数
     */
    public TextView answerTV;
    /**
     * 名字，标签
     */
    private LinearLayout headInfoLayout;
    /**
     * 回答列表listview
     */
    private MyListView myListView;
    private int accountId;
    private int questId;
    private QuestAnswerAdapter adapter;
    private Dialog dialog;

    private GridView mGridView;
    // 问题回复列表管理类
    private QAnswerListManger manager;
    // 问题回复管理类
    private QuestAnswerManager qAnswerManager;
    // 问答收藏管理类
    private AddorDelCollectManager collectManager;
    // 回复删除管理类
    private AnswerDeleteManger deleteManager;
    // 问答删除管理类
    private QuestDelManager questDelManager;
    // 问答详情管理类
    private QuestDetailManager questDetailManager;
    // 浏览次数增加
    private BrowseAddManger browseAddManger;
    private ScrollView mScrollView;
    private int isCollect = 0;
    private final int PAGE_COUNTS = 10;
    private int currentPage = 0;
    private List<QuestAnswerListData> mList = new ArrayList<QuestAnswerListData>();
    private PullToRefreshView mPullToRefreshView;
    /**
     * 删除
     */
    private TextView deleteTV;
    /**
     * 转发数
     */
    private TextView forwardTV;
    private QaResponse resp;
    private Map<Integer, String> replyMap = null;

    private RelativeLayout mInfoRL;
    private EmotionMainFragment emotionMainFragment;


    private EditText bar_edit_text;
    private ImageView bar_image_add_btn;
    private Button bar_btn_send;
    private InputMethodManager mInputManager;//软键盘管理类
    private CommentLongClickHelper commentLongClickHelper;
    private QaDataChangeManager qaDataChangeManager;
    private PraiseManger praiseManger;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 系统版本大于19
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }

        setContentView(R.layout.activity_qa_detail);
        qaDataChangeManager = QaDataChangeManager.getInstance();
        initWattingView();
        initBaseView();
        initView();
        initEmotionMainFragment();
        pullData();
        initData();
        requestData(0);
    }

    /**
     * 初始化表情面板
     */
    public void initEmotionMainFragment() {
        initEmojiView();
        mInputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, true);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, false);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(mInfoRL, bar_image_add_btn, bar_edit_text);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    private void pullData() {
        Intent intent = getIntent();
        resp = new QaResponse();
        Bundle bundle = intent.getBundleExtra(Const.QA_DATA_BUNDLE);
        if (null != bundle) {
            resp.headPic = bundle.getString(Const.BUNDLE_HEADPIC);
            resp.realName = bundle.getString(Const.BUNDLE_REALNAME);
            resp.label = bundle.getString(Const.BUNDLE_LABEL);
            resp.userInfo.sex = bundle.getInt(Const.INTENT_SEX);
            resp.userInfo.isIndustryAuthority = bundle.getBoolean(Const.INTENT_IS_MESSAGE);
            resp.content = bundle.getString(Const.BUNDLE_CONTENT);
            resp.visitorCount = bundle.getInt(Const.BUNDLE_VISITORCOUNT);
            resp.forwardCount = bundle.getInt(Const.BUNDLE_FORWARDCOUNT);
            resp.questImgs = bundle.getString(Const.BUNDLE_QUESTIMGS);
            resp.noticeJson = bundle.getString(Const.BUNDLE_NOTICEJSON);
            resp.goodCount = bundle.getInt(Const.BUNDLE_GOODCOUNT);
            resp.answerCount = bundle.getInt(Const.BUNDLE_ANSWERCOUNT);
            resp.accountId = accountId = bundle.getInt(Const.BUNDLE_ACCOUNTID);
            resp.id = questId = bundle.getInt(Const.BUNDLE_QUESTID);
            resp.isGood = bundle.getInt(Const.BUNDLE_ISGOOD);

            display(resp);
        }


    }

    private void initWattingView() {
        waittingLayout = (LinearLayout) findViewById(R.id.waitting_layout);
        waittingProBar = (ProgressBar) findViewById(R.id.waitting_progress);
        waittingTV = (TextView) findViewById(R.id.waitting_text_desc);
    }

    private void initView() {
        myListView = (MyListView) findViewById(R.id.qa_detail_list);

        mPullToRefreshView.setOnFooterRefreshListener(this);
        mPullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    private void initData() {
        String id = getIntent().getStringExtra(Const.INTENT_SCHEME_ID);
        if (null != id) {
            questId = Integer.valueOf(id);
            // 单独请求下detail接口
            questDetailManager = new QuestDetailManager(this);
            questDetailManager.addQuestDetailListener(this);
            questDetailManager.questDetail(GlobalContext.getAccountId(), questId);
        }

        browseAddManger = new BrowseAddManger(this);
        browseAddManger.browseAdd(GlobalContext.getAccountId(), questId);
        manager = new QAnswerListManger(this);
        manager.addListener(this);
        collectManager = new AddorDelCollectManager(this);
        collectManager.addAddorDelCollectListener(this);
        deleteManager = new AnswerDeleteManger(this);
        deleteManager.addAnswerDeleteListener(this);
        qAnswerManager = new QuestAnswerManager(this);
        qAnswerManager.addQuestAnswerListener(this);
        questDelManager = new QuestDelManager(this);
        questDelManager.addQuestDelListener(this);
        adapter = new QuestAnswerAdapter(this);
        adapter.addData(mList, new QuestAnswerCountsData());
        myListView.setAdapter(adapter);
        setListViewHeightBasedOnChildren(myListView);

        // 回复@功能监听
        ReplyHelper.getInstance().addReplyListener(this);
        commentLongClickHelper = CommentLongClickHelper.getInstance();
        commentLongClickHelper.addCommentLongClickListener(this);

    }

    private void initBaseView() {
        backBtn = (ImageButton) findViewById(R.id.back_button);
        backBtn.setOnClickListener(this);
        titleTV = (TextView) findViewById(R.id.title);
        titleTV.setText(getResources().getString(R.string.check_qa));
        rightImageBtn = (ImageButton) findViewById(R.id.right_imagebutton);
        rightImageBtn.setVisibility(View.VISIBLE);
        rightImageBtn.setImageResource(R.drawable.sandian);
        rightImageBtn.setOnClickListener(this);

        mPullToRefreshView = (PullToRefreshView) findViewById(R.id.qa_pull_to_refresh_view);
        mScrollView = (ScrollView) findViewById(R.id.qa_scrollview);
        headIV = (ImageView) findViewById(R.id.user_head);
        nameTV = (TextView) findViewById(R.id.user_name);
        labelTV = (TextView) findViewById(R.id.user_label);
        sexIV = (ImageView) findViewById(R.id.user_sex);
        addV = (ImageView) findViewById(R.id.add_v_iv);
        contentTV = (SpanTextView) findViewById(R.id.qa_detail_content);
        headInfoLayout = (LinearLayout) findViewById(R.id.qa_detail_headInfoLayout);
        mGridView = (GridView) findViewById(R.id.qa_detail_gridview);
        visitorTV = (TextView) findViewById(R.id.include_visitor_tv);
        deleteTV = (TextView) findViewById(R.id.include_delete_tv);
        forwardTV = (TextView) findViewById(R.id.include_forward_tv);
        praiseTV = (TextView) findViewById(R.id.include_praise_tv);
        answerTV = (TextView) findViewById(R.id.include_answer_tv);
        forwardTV.setOnClickListener(this);
        deleteTV.setOnClickListener(this);
        headInfoLayout.setOnClickListener(this);
        praiseTV.setOnClickListener(this);


        headIV.setOnClickListener(this);
        headInfoLayout.setOnClickListener(this);
        mInfoRL = (RelativeLayout) findViewById(R.id.content_relayout);

    }

    private void initEmojiView() {
        bar_image_add_btn = (ImageView) findViewById(R.id.bar_image_add_btn);
        bar_btn_send = (Button) findViewById(R.id.bar_btn_send);
        bar_btn_send.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(QaDetailActivity.this, "请输入你的评论!");
                    return;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
            }
        });
        bar_edit_text = (EditText) findViewById(R.id.bar_edit_text);
        bar_edit_text.setOnClickListener(this);
        bar_edit_text.setOnEditorActionListener(actionListener);
        bar_edit_text.addTextChangedListener(watcher);
        if (!GlobalContext.getPerfectData()) {
            bar_edit_text.setFocusable(false);
            bar_btn_send.setFocusable(false);
            bar_image_add_btn.setVisibility(View.GONE);
        } else {
            bar_edit_text.setFocusable(true);
        }
    }


    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            // 注释这段代码 这个会双击才能退出
            //super.onBackPressed();
            finish();
        }
    }

    private void requestData(int page) {
        manager.requestAnswerList(GlobalContext.getAccountId(), String.valueOf(questId), page * PAGE_COUNTS, PAGE_COUNTS);
    }

    // 上拉刷新数据请求
    private void pullUpRequest() {
        //没有搜索结果 或者数据为空 上拉没有效果
        currentPage++;
        requestData(currentPage);
    }

    OnLongClickListener longClickListener = new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            showCopyDialog();
            return true;
        }
    };


    OnEditorActionListener actionListener = new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

            if (actionId == EditorInfo.IME_ACTION_SEND /*||(event!=null&&event.getKeyCode()== KeyEvent.KEYCODE_ENTER)*/) {
                String comment = bar_edit_text.getText().toString().trim();
                if (null == comment || "".equals(comment)) {
                    Notification.toast(QaDetailActivity.this, "请输入你的评论!");
                    return false;
                }
                addAnswerComment(comment);
                // 隐藏键盘
                emotionMainFragment.onBackPress();
                return true;
            }
            return false;
        }

    };

    private void addAnswerComment(String comment) {
        if (null != replyMap) {
            for (Map.Entry<Integer, String> entry : replyMap.entrySet()) {
                comment = "回复" + entry.getValue() + ":" + comment;
            }
        }
        // 回复之前 增加等待框
        dialog = LoadingWaitDialog.createLoadingDialog(this, "");
        dialog.setCancelable(false);
        dialog.show();
        qAnswerManager.addResponse(GlobalContext.getAccountId(), questId, comment, JsonUtil.mapToStringJson(replyMap));
    }

    @Override
    public void onQuestDelFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onQuestDelSuccess() {
        // 通知其它界面数据改变
        qaDataChangeManager.notifyRemove(questId);
        this.finish();
    }

    @Override
    public void onQuestDetailFailure(int errorCode, String errorMsg) {

    }

    /**
     * 问答详情（不包括回复数）
     *
     * @param response
     */
    @Override
    public void onQuestDetailSuccess(QaResponse response) {
        if (null != response) {
            display(response);
        }
    }

    @Override
    public void commentLongClick(final QuestAnswerListData data) {
        deleteManager.delete(data.id);
        adapter.deleteById(data.id);
        // 删除后，回复数减一
        resp.answerCount--;
        Utils.showPriseCounts(resp.answerCount, answerTV);
        qaDataChangeManager.replyNotify(questId, resp.answerCount);
    }

    class MyItemClickListener implements OnItemClickListener {

        private ArrayList<String> url;

        public MyItemClickListener(ArrayList<String> url) {
            this.url = url;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // TODO Auto-generated method stub
            // 弹出图片查看按钮
            imageBrower(position, url);
        }
    }

    /**
     * 打开图片查看器
     *
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(this, position, urls2);
    }

    @Override
    public void onQuestAnswerListFailure(int errorCode, String errorMsg) {

        if (errorCode == ErrorCode.QA_ALEARY_DEL) {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText(errorMsg == null ? "" : errorMsg);
            mPullToRefreshView.onFooterRefreshComplete();
            // 问答已被删除 通知其它界面数据改变
            qaDataChangeManager.notifyRemove(questId);
        } else {
            waittingLayout.setVisibility(View.VISIBLE);
            waittingProBar.setVisibility(View.GONE);
            waittingTV.setText("加载失败，请稍后再试...");
            mPullToRefreshView.onFooterRefreshComplete();
        }
    }

    @Override
    public void onQuestAnswerListSuccess(List<QuestAnswerListData> objdata,
                                         QuestAnswerCountsData qacd) {
        waittingLayout.setVisibility(View.GONE);
        isCollect = qacd.isCollect;
        mPullToRefreshView.onFooterRefreshComplete();
        if (null != objdata) {
            adapter.addData(objdata, qacd);
            mList = adapter.getList();
            adapter.notifyDataSetChanged();
            if(0 == currentPage){
                mScrollView.fullScroll(ScrollView.FOCUS_UP);
            }
            setListViewHeightBasedOnChildren(myListView);
            updateCounts(qacd);
        }

    }

    private void display(QaResponse response) {
        this.resp = response;
        PictureDownloadUtils.displayHeadImage(this, headIV, resp.headPic);
        nameTV.setText(resp.realName == null ? "" : resp.realName);
        labelTV.setText(resp.label == null ? "" : resp.label);
        Utils.showSex(this, resp.userInfo.sex, sexIV);
        if (resp.accountId == GlobalContext.getAccountId()) {
            deleteTV.setVisibility(View.VISIBLE);
        } else {
            deleteTV.setVisibility(View.INVISIBLE);
        }
        Utils.showAuth(resp.userInfo, addV);

        Utils.showSpanContentNoClick(this, resp.content, resp.noticeJson, contentTV);
//        contentTV.setAutoLinkMask(Linkify.WEB_URLS);
        contentTV.setOnLongClickListener(longClickListener);
        Utils.showVisitorCounts(resp.visitorCount, visitorTV);
        Utils.showPriseCounts(resp.answerCount, answerTV);
        Utils.praiseChanged(this, resp.isGood, resp.goodCount, praiseTV);
        // 通知界面 浏览数发生更新
        qaDataChangeManager.updateVisitor(resp.id, resp.visitorCount);
        // 通知界面 点赞数发生更新
        qaDataChangeManager.priseNotify(resp.id, resp.isGood, resp.goodCount);
        // 通知界面 回复数发生更新
        qaDataChangeManager.replyNotify(resp.id, resp.answerCount);


        if (TextUtils.isEmpty(resp.questImgs)) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(10, 5);
            mGridView.setLayoutParams(lp);
            mGridView.setVisibility(View.INVISIBLE);
        } else {
            mGridView.setVisibility(View.VISIBLE);
            ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
            double multiple = Math.ceil((float) imageUrls.size() / GlobalContext.NUMCOLUMNS);
            int height = (int) (Utils.dip2px(this, 80) * multiple + (multiple - 1) * Utils.dip2px(this, 10));
            int width = 0;
            if (multiple >= 1) {
                width = Utils.dip2px(this, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS - 1) * Utils.dip2px(this, 5);
            } else {
                width = Utils.dip2px(this, 80) * imageUrls.size() + (imageUrls.size() - 1) * Utils.dip2px(this, 5);
            }
            width = width + Utils.dip2px(this, 10);// 加上pendingLeft 10dp
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
            mGridView.setLayoutParams(lp);
            mGridView.setAdapter(new NoScrollGridAdapter(this, imageUrls));
            // 点击回帖九宫格，查看大图
            mGridView.setOnItemClickListener(new MyItemClickListener(imageUrls));
        }


    }

    private void updateCounts(QuestAnswerCountsData qacd) {
        if (null != qacd) {
            resp.goodCount = qacd.goodCount;
            resp.answerCount = qacd.answerCount;
            resp.visitorCount = qacd.visitorCount;
            Utils.showVisitorCounts(qacd.visitorCount, visitorTV);
            Utils.showPriseCounts(qacd.goodCount, praiseTV);
            Utils.showPriseCounts(qacd.answerCount, answerTV);
            // 通知界面 浏览数发生更新
            qaDataChangeManager.updateVisitor(questId, qacd.visitorCount);
            // 通知界面 点赞数发生更新
            qaDataChangeManager.priseNotify(questId, resp.isGood, qacd.goodCount);
            // 通知界面 回复数发生更新
            qaDataChangeManager.replyNotify(questId, qacd.answerCount);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.include_delete_tv:// 问答删除
                CustomDialog.Builder builder = new CustomDialog.Builder(QaDetailActivity.this);
                builder.setTitle("确认删除该条问答吗？");
                builder.setPositiveButton(getResources().getString(R.string.confirm),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                questDelManager.deleteQuest(GlobalContext.getAccountId(), questId);
                            }
                        });
                builder.setNegativeButton(getResources().getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.create().show();
                break;
            case R.id.include_forward_tv:    // 转发
                String imageUrl = null;
                if (TextUtils.isEmpty(resp.questImgs)) {
                    imageUrl = GlobalContext.cdndownUrl + resp.headPic;
                } else {
                    ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
                    imageUrl = imageUrls.get(0);
                }
                ShareSDKManager shareSDKManager = ShareSDKManager.getInstance();
                shareSDKManager.showShare(QaDetailActivity.this, resp.content, 1, imageUrl, questId);
                break;
            case R.id.bar_edit_text:
                if (!GlobalContext.getPerfectData()) {
                    Notification.toast(this, "您还未完善资料，无法回复");
                }
                break;
            case R.id.include_praise_tv:
                if (0 == resp.isGood) {
                    resp.isGood = 1;
                    resp.goodCount++;
                } else {
                    resp.isGood = 0;
                    resp.goodCount--;
                }
                Utils.praiseChanged(this, resp.isGood, resp.goodCount, praiseTV);
                qaDataChangeManager.priseNotify(questId, resp.isGood, resp.goodCount);
                // 请求点赞接口
                praiseManger = new PraiseManger(this);
                praiseManger.addPraiseListener(QaDetailActivity.this);
                praiseManger.praise(GlobalContext.getAccountId(), questId);
                // 判断以前点赞状态
                break;
            case R.id.back_button:
                finish();
                break;
            case R.id.qa_detail_headInfoLayout:
            case R.id.user_head:
                Utils.intoHeadInfoActivity(accountId, QaDetailActivity.this);
                break;
            case R.id.right_imagebutton:
                showDialog();
                break;
            case R.id.custom_qa_btn:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (checkLevel()) {
                    Intent ask = new Intent();
                    ask.setClass(QaDetailActivity.this, AskActivity.class);
                    startActivity(ask);
                } else {
                    ErrorDialogHelper.getInstance().showPerfectAuth(this);
                }
                break;
            case R.id.custom_am_btn:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                Intent anonymous = new Intent();
                anonymous.setClass(QaDetailActivity.this, AmQuestionActivity.class);
                startActivity(anonymous);
                break;
            case R.id.close_Dialog:
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                break;

            default:
                break;
        }
    }

    @Override
    public void onPraiseFailure(int errorCode, String errorMsg) {
    }

    @Override
    public void onPraiseSuccess() {
    }

    @Override
    public void onQuestAnswerFailure(int errorCode, String errorMsg) {
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    @Override
    public void onQuestAnswerSuccess(QuestAnswerListData qacd) {
        // TODO Auto-generated method stub
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        // 评论完成 添加一条记录到回复列表
        if (null != qacd) {
            bar_edit_text.setText("");
            bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
            if (null != replyMap) {
                replyMap.clear();
            }
            qacd.accountId = GlobalContext.getAccountId();
            qacd.goodCount = 0;
            adapter.addOneData(qacd);
            adapter.notifyDataSetChanged();
            // 添加一条回答数
            resp.answerCount++;
            Utils.showPriseCounts(resp.answerCount, answerTV);
            qaDataChangeManager.replyNotify(questId, resp.answerCount);
            mScrollView.fullScroll(ScrollView.FOCUS_UP);
            setListViewHeightBasedOnChildren(myListView);
//			new Handler().post(new Runnable() {
//				@Override
//				public void run() {
//				}
//			});

        }

    }

    public boolean checkLevel() {
        boolean ret = false;
        if (GlobalContext.getPerfectData()) {
            // 提示用户完成认证 必须达到一级认证才能提问
            ret = true;
        }
        return ret;
    }

    /**
     * 显示复制弹出框
     */
    private void showCopyDialog() {
        commentLongClickHelper.showCopyDialog(this, contentTV.getText().toString());
    }

    /**
     * 显示收藏取消弹出框
     */
    private void showDialog() {
        commentLongClickHelper.showCollectReportDialog(this, collectManager, isCollect, questId);
    }

    @Override
    public void onAddorDelCollectFailure(int errorCode, String errorMsg) {
    }

    @Override
    public void onAddorDelCollectSuccess() {
        // TODO Auto-generated method stub
        if (1 == isCollect) {
            isCollect = 0;
            Notification.toast(this, "取消收藏成功");
        } else {
            isCollect = 1;
            Notification.toast(this, "收藏成功");
        }

    }

    /**
     * 问题回答删除
     *
     * @param errorCode
     * @param errorMsg
     */
    @Override
    public void onAnswerDeleteFailure(int errorCode, String errorMsg) {

    }

    @Override
    public void onAnswerDeleteSuccess() {

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);

    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        int totalHeight = 0;
        for (int i = 0, len = adapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = adapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    /* (non-Javadoc)		上拉刷新...
     * @see com.wbao.dianniu.scrollview.PullToRefreshView.OnFooterRefreshListener#onFooterRefresh(com.wbao.dianniu.scrollview.PullToRefreshView)
     */
    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullUpRequest();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ReplyHelper.getInstance().removeReplyListener(this);
        if (null != commentLongClickHelper) {
            commentLongClickHelper.removeCommentLongClickListener(this);
        }
        if (null != dialog && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (null != questDetailManager) {
            questDetailManager.removeQuestDetailListener(this);
        }
        if (null != manager) {
            manager.removeListener(this);
        }
        if (null != collectManager) {
            collectManager.removeAddorDelCollectListener(this);
        }
        if (null != deleteManager) {
            deleteManager.removeAnswerDeleteListener(this);
        }
        if (null != qAnswerManager) {
            qAnswerManager.removeQuestAnswerListener(this);
        }
        if (null != questDelManager) {
            questDelManager.removeQuestDelListener(this);
        }
        if (null != praiseManger) {
            praiseManger.removePraiseListener(this);
        }


    }

    /**
     * @param userName
     * @param userId
     * @回复按钮毁掉
     */
    @Override
    public void reply(String userName, int userId) {

        bar_edit_text.setText("");
        bar_edit_text.setHint("回复:" + userName);
        if (bar_edit_text.isFocusable()) {
            bar_edit_text.requestFocus();
        }
        bar_edit_text.post(new Runnable() {
            @Override
            public void run() {
                mInputManager.showSoftInput(bar_edit_text, 0);
            }
        });
        // add Reply logical
        replyMap = new HashMap<Integer, String>();
        replyMap.put(userId, userName);
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                // 清空输入内容时，清除@效果的hashMap
                bar_edit_text.setHint(getResources().getString(R.string.qa_detail_hint));
                if (null != replyMap) {
                    replyMap.clear();
                }
            }
        }
    };

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
    }

    float previousX = 0;
    float previousY = 0;
    float softHeight = 0;
    boolean inOutside = true;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                previousX = ev.getRawX();
                previousY = ev.getRawY();
                int[] l = {0, 0};
                bar_image_add_btn.getLocationInWindow(l);
                softHeight = l[1];
                if (ev.getY() < softHeight) {
                    inOutside = true;
                } else {
                    inOutside = false;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                float dy = previousY - ev.getRawY();
                float dx = previousX - ev.getRawX();
                if ((Math.abs(dy) > 30 || Math.abs(dx) > 30) && inOutside) {
                    hideKeyboard();
                }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard() {
        emotionMainFragment.onBackPress();
    }

}
